package archer.framework.utils;

import java.util.Collection;
import java.util.Iterator;

import eu.medsea.mimeutil.MimeException;
import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author christ
 * @date 2016/7/4
 */
public class MimeUtils {

    private static final Logger logger = LoggerFactory.getLogger(MimeUtils.class);

    private static MimeUtil2 mimeUtil;

    static {
        mimeUtil = new MimeUtil2();
        mimeUtil.registerMimeDetector("eu.medsea.mimeutil.detector.MagicMimeMimeDetector");
    }

    public static String getMimeType(byte[] data) {
        try {
            @SuppressWarnings("unchecked")
            Collection<MimeType> mimeTypes = mimeUtil.getMimeTypes(data);
            if (mimeTypes != null) {
                Iterator<MimeType> mimeTypeIterator = mimeTypes.iterator();
                if (mimeTypeIterator.hasNext()) {
                    return mimeTypeIterator.next().toString();
                }
            }
        } catch (MimeException e) {
            logger.warn("Failed to detect mime type from file data", e);
        }
        return MimeUtil2.UNKNOWN_MIME_TYPE.toString();
    }
}
